package com.design.YiTong.shop.receiver;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.design.YiTong.model.medicinal.MedicinalOrder;
import com.design.YiTong.model.medicinal.MedicinalShop;
import com.design.YiTong.shop.service.OrderService;
import com.design.YiTong.shop.service.ShopService;
import com.design.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderReceiver {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopService shopService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public boolean receiver(MedicinalOrder medicinalOrder, Message message, Channel channel) throws IOException {
        MedicinalShop medicinalShop=shopService.searchById(medicinalOrder.getMedicinal_id());
        if(medicinalShop.getAvailableNumber()<0){
            medicinalShop.setAvailableNumber(medicinalShop.getAvailableNumber()+medicinalOrder.getNums());
            shopService.updateById(medicinalShop);
            return false;
        }
        orderService.saveOrder(medicinalOrder);
        return true;
    }

}
